<template>
  <view class="container">
    <!-- 订单详情 -->
    <view class="order-detail" v-if="currentOrder">
      <view class="order-header">
        <text class="order-title">订单详情</text>
        <text class="order-status">{{currentOrder.status || '待支付'}}</text>
      </view>
      <view class="order-info">
        <view class="info-item">
          <text class="info-label">订单编号：</text>
          <text class="info-value">{{currentOrder.orderId}}</text>
        </view>
        <view class="info-item">
          <text class="info-label">下单时间：</text>
          <text class="info-value">{{currentOrder.createTime}}</text>
        </view>
        <view class="info-item">
          <text class="info-label">支付金额：</text>
          <text class="info-value price">¥{{currentOrder.money}}</text>
        </view>
      </view>
    </view>
    
    <!-- 商品图片 -->
    <image v-else class="product-image" :src="plotInfo.imageUrl || 'http://121.36.197.175:19000/test/swiper1.jpg'" mode="aspectFill"></image>
    
    <!-- 商品信息 -->
    <view class="product-info">
      <view class="product-header">
        <view class="product-title">{{plotInfo.position || '未知地块'}}</view>
        <!-- <view class="product-location" v-if="plotInfo.position">位置：{{plotInfo.position}}</view> -->
      </view>
      
      <view class="price-section">
        <view class="current-price">
          <text class="price-symbol">¥</text>
          <text class="price-value">{{isSeckill ? seckillInfo.price : plotInfo.price}}</text>
        </view>
        <view class="original-price" v-if="isSeckill">
          <text>原价：</text>
          <text class="price-through">¥{{plotInfo.price}}</text>
        </view>
      </view>
      
      <!-- 秒杀信息 -->
      <view class="seckill-info" v-if="isSeckill">
        <view class="seckill-timer" v-if="!isExpired">
          <text class="timer-label">距结束还剩：</text>
          <view class="countdown-box">
            <text class="time-unit">{{countdown.hours}}</text>
            <text class="time-separator">:</text>
            <text class="time-unit">{{countdown.minutes}}</text>
            <text class="time-separator">:</text>
            <text class="time-unit">{{countdown.seconds}}</text>
          </view>
        </view>
        <view class="stock-info">
          <text>库存：{{seckillInfo.remain}}/{{seckillInfo.total}}</text>
          <view class="progress-bar">
            <view class="progress" :style="{width: progressPercent + '%'}"></view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 购买数量 -->
    <view class="quantity-section">
      <text class="section-title">购买数量</text>
      <view class="quantity-control">
        <button class="quantity-btn" @click="decreaseQuantity" :disabled="quantity <= 1">-</button>
        <input class="quantity-input" type="number" v-model="quantity" :disabled="isSeckill"/>
        <button class="quantity-btn" @click="increaseQuantity" :disabled="isMaxQuantity">+</button>
      </view>
    </view>
    
    <!-- 总价 -->
    <view class="total-section">
      <text class="total-label">总价：</text>
      <text class="total-price">¥{{totalPrice}}</text>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <button class="submit-btn" 
              :disabled="isDisabled" 
              :class="{'btn-disabled': isDisabled}"
              @click="handleSubmit">
        {{submitButtonText}}
      </button>
    </view>
  </view>
</template>

<script>
export default {
    data() {
        return {
            plotInfo: {}, // 地块基本信息
            seckillInfo: null, // 秒杀信息
            quantity: 1, // 购买数量
            userId: '', // 用户ID
            countdown: {
                hours: '00',
                minutes: '00',
                seconds: '00'
            },
            timer: null, // 倒计时定时器
            currentOrder: null, // 当前订单信息
            showResult: false // 是否显示结果弹窗
        }
    },
    computed: {
        isSeckill() {
            return !!this.seckillInfo
        },
        isExpired() {
            if (!this.seckillInfo) return true
            const now = new Date().getTime()
            const endTime = this.seckillInfo.startTime + this.seckillInfo.duration
            return now > endTime
        },
        progressPercent() {
            if (!this.seckillInfo) return 0
            const sold = this.seckillInfo.total - this.seckillInfo.remain
            return (sold / this.seckillInfo.total) * 100
        },
        isMaxQuantity() {
            if (this.isSeckill) {
                return this.quantity >= this.seckillInfo.remain || this.quantity >= this.seckillInfo.limitNum
            }
            return this.quantity >= this.plotInfo.stock
        },
        totalPrice() {
            const price = this.isSeckill ? this.seckillInfo.price : this.plotInfo.price
            return (price * this.quantity).toFixed(2)
        },
        isDisabled() {
            return this.isExpired || (this.isSeckill && this.seckillInfo.remain <= 0)
        },
        submitButtonText() {
            if (this.isExpired) return '活动已结束'
            if (this.isSeckill && this.seckillInfo.remain <= 0) return '已抢光'
            return this.isSeckill ? '立即抢购' : '立即购买'
        }
    },
    onLoad(options) {
        // 获取用户信息
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
            this.userId = userInfo.userId
        }

        // 根据路由参数加载数据
        if (options.skId) {
            this.loadSeckillDetail(options.skId)
            // 如果有订单ID，加载订单信息
            if (options.orderId) {
                this.loadOrderDetail(options.orderId)
            }
        } else if (options.plotId) {
            this.loadPlotDetail(options.plotId)
        }
    },
    onUnload() {
        // 清除定时器
        if (this.timer) {
            clearInterval(this.timer)
            this.timer = null
        }
    },
    methods: {
        // 加载秒杀详情
        loadSeckillDetail(skId) {
            uni.request({
                url: `/secondkill/detail/${skId}`,
                method: 'GET',
                success: (res) => {
                    if (res.data && res.data.code === 200) {
                        const detail = res.data.data.detail
                        this.plotInfo = detail.land || {}
                        this.seckillInfo = {
                            skId: detail.secondkill.skid,
                            price: detail.secondkill.skprice,
                            total: detail.secondkill.sknum,
                            remain: detail.secondkill.sknum - (detail.secondkill.soldnum || 0),
                            limitNum: detail.secondkill.limitnum,
                            startTime: this.parseTimeToTimestamp(detail.secondkill.skstarttime),
                            duration: detail.secondkill.sktime * 3600 * 1000
                        }
                        this.startCountdown()
                    }
                }
            })
        },
        // 加载普通地块详情
        loadPlotDetail(plotId) {
            uni.request({
                url: `/land/${plotId}`,
                method: 'GET',
                success: (res) => {
                    if (res.data && res.data.code === 200) {
                        this.plotInfo = res.data.data
                    }
                }
            })
        },
        // 开始倒计时
        startCountdown() {
            if (this.timer) clearInterval(this.timer)

            this.timer = setInterval(() => {
                const now = new Date().getTime()
                const endTime = this.seckillInfo.startTime + this.seckillInfo.duration
                let remainTime = endTime - now

                if (remainTime <= 0) {
                    clearInterval(this.timer)
                    this.countdown = { hours: '00', minutes: '00', seconds: '00' }
                    return
                }

                const hours = Math.floor(remainTime / (1000 * 60 * 60))
                remainTime -= hours * 1000 * 60 * 60
                const minutes = Math.floor(remainTime / (1000 * 60))
                remainTime -= minutes * 1000 * 60
                const seconds = Math.floor(remainTime / 1000)

                this.countdown = {
                    hours: hours.toString().padStart(2, '0'),
                    minutes: minutes.toString().padStart(2, '0'),
                    seconds: seconds.toString().padStart(2, '0')
                }
            }, 1000)
        },
        // 解析时间戳
        parseTimeToTimestamp(timeValue) {
            if (typeof timeValue === 'string') {
                if (timeValue.includes('T') || timeValue.includes('-')) {
                    return new Date(timeValue).getTime()
                } else if (!isNaN(timeValue)) {
                    const timestamp = parseInt(timeValue)
                    return timestamp < 1000000000000 ? timestamp * 1000 : timestamp
                }
            } else if (typeof timeValue === 'number') {
                return timeValue < 1000000000000 ? timeValue * 1000 : timeValue
            }
            return new Date().getTime()
        },
        // 减少数量
        decreaseQuantity() {
            if (this.quantity > 1) {
                this.quantity--
            }
        },
        // 增加数量
        increaseQuantity() {
            if (!this.isMaxQuantity) {
                this.quantity++
            }
        },
        // 提交订单
        handleSubmit() {
            if (!this.userId) {
                uni.showModal({
                    title: '提示',
                    content: '请先登录',
                    success: (res) => {
                        if (res.confirm) {
                            uni.navigateTo({
                                url: '/pages/login/login'
                            })
                        }
                    }
                })
                return
            }

            if (this.isDisabled) return

            if (this.isSeckill) {
                this.executeSecondKill({
                    skId: this.seckillInfo.skId,
                    landId: this.plotInfo.landid
                })
            } else {
                // 普通购买逻辑
                const orderData = {
                    userId: this.userId,
                    num: this.quantity,
                    landId: this.plotInfo.landid
                }

                uni.request({
                    url: '/land/order',
                    method: 'POST',
                    data: orderData,
                    success: (res) => {
                        if (res.data && res.data.code === 200) {
                            const orderId = res.data.data.orderId
                            this.currentOrder = {
                                orderId: orderId,
                                createTime: new Date().toLocaleString(),
                                money: this.totalPrice,
                                status: '待支付'
                            }
                        } else {
                            uni.showToast({
                                title: res.data.message || '下单失败',
                                icon: 'none'
                            })
                        }
                    }
                })
            }
        },

        // 执行秒杀
        executeSecondKill(item) {
            uni.showLoading({
                title: '抢购中...'
            })

            uni.request({
                url: '/secondkill/order',
                method: 'POST',
                header: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': uni.getStorageSync('token')
                },
                data: {
                    skId: item.skId,
                    landId: item.landId,
                    userId: this.userId,
                    num: this.quantity
                },
                success: (res) => {
                    uni.hideLoading()

                    if (res.data && res.data.code === 200) {
                        // 秒杀成功，获取订单ID
                        const orderId = res.data.data.orderId
                        const orderDetail = res.data.data.orderDetail

                        // 显示抢购成功提示
                        uni.showModal({
                            title: '抢购成功',
                            content: `恭喜您抢购成功！\n订单编号：${orderId}\n商品：${this.plotInfo.position}\n数量：${this.quantity}块\n总价：￥${orderDetail.order.money}`,
                            showCancel: false,
                            success: () => {
                                // 显示支付确认框
                                uni.showModal({
                                    title: '支付确认',
                                    content: `是否立即使用余额支付￥${orderDetail.order.money}？`,
                                    cancelText: '稍后支付',
                                    confirmText: '立即支付',
                                    success: (confirmRes) => {
                                        if (confirmRes.confirm) {
                                            // 调用支付接口
                                            this.payOrder(orderId)
                                        } else {
                                            // 用户选择稍后支付
                                            uni.showToast({
                                                title: '您可以在订单列表中继续支付',
                                                icon: 'none',
                                                duration: 2000
                                            })
                                            
                                            // 延迟返回商城页面
                                            setTimeout(() => {
                                                // 清除计时器
                                                if (this.timer) {
                                                    clearInterval(this.timer);
                                                    this.timer = null;
                                                }
                                                
                                                uni.navigateBack({
                                                    delta: 1
                                                });
                                            }, 2000);
                                        }
                                    }
                                })
                            }
                        })
                    } else {
                        // 秒杀失败
                        uni.showToast({
                            title: res.data.message || '抢购失败，请稍后再试',
                            icon: 'none'
                        })
                    }
                },
                fail: (err) => {
                    uni.hideLoading()

                    uni.showToast({
                        title: '网络异常，请稍后再试',
                        icon: 'none'
                    })
                }
            })
        },

        // 支付订单
        payOrder(orderId) {
            uni.showModal({
                title: '确认支付',
                content: '是否确认支付该订单？',
                success: (res) => {
                    if (res.confirm) {
                        uni.showModal({
                            title: '请输入支付密码',
                            editable: true,
                            placeholderText: '请输入6位数字密码',
                            success: (passwordRes) => {
                                if (passwordRes.confirm) {
                                    // 手动验证输入是否为6位数字
                                    if (/^\d{6}$/.test(passwordRes.content)) {
                                        // 验证支付密码
                                        if (passwordRes.content === '123456') {
                                            uni.showLoading({
                                                title: '支付处理中...'
                                            });

                                            uni.request({
                                                url: `/secondkill/pay/${orderId}`,
                                                method: 'POST',
                                                header: {
                                                    'Content-Type': 'application/x-www-form-urlencoded',
                                                    'Authorization': uni.getStorageSync('token')
                                                },
                                                success: (res) => {
                                                    uni.hideLoading();
                                                    if (res.data && res.data.code === 200) {
                                                        uni.showToast({
                                                            title: '支付成功',
                                                            icon: 'success'
                                                        });
                                                        // 更新当前订单状态
                                                        if (this.currentOrder) {
                                                            this.currentOrder.status = '已支付';
                                                        }
                                                        // 刷新订单数据
                                                        this.loadOrderDetail(orderId);
                                                        
                                                        // 延迟一段时间后返回商城首页
                                                        setTimeout(() => {
                                                            // 清除计时器
                                                            if (this.timer) {
                                                                clearInterval(this.timer);
                                                                this.timer = null;
                                                            }
                                                            
                                                            uni.navigateBack({
                                                                delta: 1
                                                            });
                                                        }, 1500);
                                                    } else {
                                                        uni.showToast({
                                                            title: res.data.message || '支付失败',
                                                            icon: 'none'
                                                        });
                                                    }
                                                },
                                                fail: (err) => {
                                                    uni.hideLoading();
                                                    uni.showToast({
                                                        title: '支付失败，请稍后重试',
                                                        icon: 'none'
                                                    });
                                                }
                                            });
                                        } else {
                                            uni.showToast({
                                                title: '支付密码错误',
                                                icon: 'none'
                                            });
                                        }
                                    } else {
                                        uni.showToast({
                                            title: '请输入6位数字密码',
                                            icon: 'none'
                                        });
                                    }
                                }
                            }
                        });

                        // 尝试强制设置为密码输入框
                        setTimeout(() => {
                            const inputs = document.querySelectorAll('.uni-modal input');
                            if (inputs && inputs.length > 0) {
                                inputs[0].type = 'password';
                            }
                        }, 300);
                    }
                }
            });
        },

        // 加载订单详情
        loadOrderDetail(orderId) {
            uni.request({
                url: `/secondkill/order/${orderId}`,
                method: 'GET',
                success: (res) => {
                    if (res.data && res.data.code === 200) {
                        const orderDetail = res.data.data
                        this.currentOrder = {
                            orderId: orderDetail.orderId,
                            createTime: orderDetail.createTime || new Date().toLocaleString(),
                            money: orderDetail.money,
                            status: orderDetail.status || '待支付'
                        }
                    }
                }
            })
        }
    }
}

</script>

<style>
.container {
  padding-bottom: 120rpx;
}

.order-detail {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.order-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.order-status {
  font-size: 28rpx;
  color: #ff6b00;
}

.order-info {
  padding: 20rpx 0;
}

.info-item {
  display: flex;
  margin-bottom: 20rpx;
}

.info-label {
  width: 160rpx;
  font-size: 28rpx;
  color: #666;
}

.info-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.info-value.price {
  color: #ff6b00;
  font-weight: bold;
}

.product-image {
  width: 100%;
  height: 600rpx;
}

.product-info {
  padding: 30rpx;
  background-color: #fff;
}

.product-header {
  margin-bottom: 20rpx;
}

.product-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.product-location {
  font-size: 28rpx;
  color: #666;
}

.price-section {
  display: flex;
  align-items: baseline;
  margin-bottom: 20rpx;
}

.current-price {
  display: flex;
  align-items: baseline;
}

.price-symbol {
  font-size: 28rpx;
  color: #ff6b00;
}

.price-value {
  font-size: 48rpx;
  font-weight: bold;
  color: #ff6b00;
  margin-right: 20rpx;
}

.original-price {
  font-size: 24rpx;
  color: #999;
}

.price-through {
  text-decoration: line-through;
}

.seckill-info {
  background-color: #fff7f7;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
}

.seckill-timer {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.timer-label {
  font-size: 26rpx;
  color: #666;
  margin-right: 20rpx;
}

.countdown-box {
  display: flex;
  align-items: center;
}

.time-unit {
  background-color: #ff6b00;
  color: #fff;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.time-separator {
  margin: 0 10rpx;
  color: #ff6b00;
  font-weight: bold;
}

.stock-info {
  font-size: 26rpx;
  color: #666;
}

.progress-bar {
  height: 10rpx;
  background-color: #ffd8cc;
  border-radius: 5rpx;
  margin-top: 10rpx;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: #ff6b00;
  transition: width 0.3s;
}

.quantity-section {
  margin-top: 20rpx;
  padding: 30rpx;
  background-color: #fff;
}

.section-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border: none;
  font-size: 36rpx;
  color: #333;
}

.quantity-btn[disabled] {
  color: #999;
  background-color: #f8f8f8;
}

.quantity-input {
  width: 100rpx;
  height: 60rpx;
  text-align: center;
  margin: 0 20rpx;
  background-color: #f5f5f5;
}

.total-section {
  margin-top: 20rpx;
  padding: 30rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.total-label {
  font-size: 30rpx;
  color: #333;
}

.total-price {
  font-size: 36rpx;
  color: #ff6b00;
  font-weight: bold;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #ff6b00;
  color: #fff;
  border-radius: 40rpx;
  font-size: 32rpx;
}

.btn-disabled {
  background-color: #ccc;
}
</style>